package com.zbkj.common.token;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.constants.RedisKeyConstants;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.exception.ExceptionCodeEnum;
import com.zbkj.common.exception.ResultException;
import com.zbkj.common.model.user.User;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.common.vo.LoginUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 * +----------------------------------------------------------------------
 * | Author:
 * +----------------------------------------------------------------------
 */
@Component
public class FrontTokenComponent {

    @Resource
    private RedisUtil redisUtil;
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    private static final Long MILLIS_MINUTE = 60 * 1000L;

    // 令牌有效期（默认30分钟） todo 调试期改为5小时
//    private static final int expireTime = 30;
    private static final int expireTime = 5 * 60;


    /**
     * 删除用户身份信息
     */
    public void delLoginToken(String token) {
        if (StrUtil.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisUtil.delete(userKey);
        }
    }

    /**
     * 获取请求token
     *
     * @param request HttpServletRequest
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(Constants.HEADER_AUTHORIZATION_KEY);
        if (StrUtil.isNotEmpty(token) && token.startsWith(Constants.USER_TOKEN_REDIS_KEY_PREFIX)) {
            token = token.replace(Constants.USER_TOKEN_REDIS_KEY_PREFIX, "");
        }
        return token;
    }

    public String getTokenKey(String uuid) {
        return Constants.USER_TOKEN_REDIS_KEY_PREFIX + uuid;
    }

    /**
     * 推出登录
     * @param request HttpServletRequest
     */
    public void logout(HttpServletRequest request) {
        String token = getToken(request);
        delLoginToken(token);
    }

    /**
     * 获取当前登录用户id
     */
    public Long getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        String idstr = redisUtil.get(getTokenKey(token));
        return StringUtils.isNotBlank(idstr) ? Long.valueOf(idstr) : null;
    }

    public Long getLoginUserId() {
        Long userId = this.getUserId();
        if(Objects.isNull(userId)) {
            throw new ResultException(ExceptionCodeEnum.UNAUTHORIZED.getCode(),"未登录或token过期，请登录！");
        }
        return userId;
    }

    /**
     * 创建登录令牌
     * @param id
     */
    public String createToken(Long id) {
        String token = UUID.randomUUID().toString().replace("-", "");
        token = String.format("%s.%s",id,token);
        redisUtil.set(getTokenKey(token), String.valueOf(id), Constants.TOKEN_EXPRESS_MINUTES, TimeUnit.MINUTES);
        return token;
    }

    public void signProcess(Long id, String newToken) {
        String singKey = String.format(RedisKeyConstants.CLIENT_SIGN_KEY,id);
        String oldToken = redisUtil.get(singKey);
        if(StringUtils.isNotBlank(oldToken)) {
            redisUtil.delete(getTokenKey(oldToken));
        }
        redisUtil.set(singKey,newToken, Constants.TOKEN_EXPRESS_MINUTES, TimeUnit.MINUTES);
    }
}
